class Solution {
public:
    int maxDistance(vector<int>& position, int m) {
        sort(position.begin(), position.end());
        int n = position.size();
        int left = 1;
        int right = position[n - 1] - position[0];

        while (left < right) {
            int mid = left + (right - left + 1) / 2;
            if (canPlaceBalls(position, m, mid)) {
                left = mid;
            }
            else {
                right = mid - 1;
            }
        }

        return left;
    }

private:
    bool canPlaceBalls(const vector<int>& position, int m, int min_dist) {
        int balls_placed = 1;
        int last_pos = position[0];

        for (int i = 1; i < position.size(); ++i) {
            int pos = position[i];
            if (pos - last_pos >= min_dist) {
                balls_placed++;
                last_pos = pos;
                if (balls_placed == m) {
                    return true;
                }
            }
        }
        return balls_placed >= m;
    }
};